package applicationServer.logic;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;

import javax.sip.address.Address;
import javax.sip.address.AddressFactory;

import applicationServer.configurationManagement.ConfigurationManager;

public class ClientManager {

	
	Hashtable<String,UserInfo> users = null;
	Hashtable<String,MediaServerInfo> mediaServers = null;
	
	Hashtable<String, ArrayList <UserInfo>> receiving = null; 
	Hashtable<String,UserInfo> lastUserAdded = null;
	
	
	public ClientManager(){
		users = new Hashtable<String, UserInfo>();
		mediaServers = new Hashtable<String, MediaServerInfo>();
		receiving = new Hashtable<String, ArrayList<UserInfo>>();

		lastUserAdded = new Hashtable<String, UserInfo>();
		
	}
	
	
	public void addMediaServer(String id, String media, String u, int port){
		
		mediaServers.put(media,new MediaServerInfo(id,u, media,port));
		receiving.put(media, new ArrayList<UserInfo>());
		
	}
	
	public void addMediaServer(MediaServerInfo msi){
		
		mediaServers.put(msi.get_media(),msi);
		receiving.put(msi.get_media(), new ArrayList<UserInfo>());
		
	}
	
	public void addUser(String id, Address u, String media){
		UserInfo ui = new UserInfo(id,u, media);
		if (!users.containsKey(id)){
			users.put(id,ui);
		}
		else{
			users.get(id).addMedia(media);
		}
		receiving.get(media).add(users.get(id));
		lastUserAdded.put(media, ui);
		
	}

	public UserInfo getLastUser(String media){
		return lastUserAdded.get(media);
	}
	
	public StreamerInfo getForwardingEntity(String media){
		if ((receiving.get(media) == null) || (receiving.get(media).size() == 0))
			return mediaServers.get(media);
		else
			return getLastUser (media);
	}


	public void loadServers(ConfigurationManager configM) {
		// TODO Auto-generated method stub
		for (int i = 0; i < configM.get_servers().size(); i++) {
			mediaServers.put(configM.get_servers().get(i).get_media(), configM.get_servers().get(i));
			receiving.put(configM.get_servers().get(i).get_media(), new ArrayList<UserInfo>());
		}
	}


	public UserInfo getUser(String string) {
		return users.get(string);
	}
	
	
	
	
}
